package com.qing.expert.modules.admin.service.impl;

import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.modules.admin.service.AdminExportService;
import com.qing.expert.modules.admin.vo.request.ExportRequest;
import com.qing.expert.modules.order.entity.Order;
import com.qing.expert.modules.order.mapper.OrderMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class AdminExportServiceImpl implements AdminExportService {

    @Resource
    private OrderMapper orderMapper;

    @Override
    public void exportOrders(ExportRequest request, HttpServletResponse response) {
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet("订单数据");

            // 创建样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle contentStyle = createContentStyle(workbook);

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = { "订单ID", "用户ID", "达人ID", "订单金额", "订单状态", "创建时间" };
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 查询订单数据
            LocalDateTime startTime = request.getStartDate().atStartOfDay();
            LocalDateTime endTime = request.getEndDate().atTime(LocalTime.MAX);
            List<Order> orders = orderMapper.selectOrderList(startTime, endTime, request.getStatus());

            // 填充数据行
            int rowNum = 1;
            for (Order order : orders) {
                Row row = sheet.createRow(rowNum++);

                Cell cell0 = row.createCell(0);
                cell0.setCellValue(order.getOrderId());
                cell0.setCellStyle(contentStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(order.getUserId());
                cell1.setCellStyle(contentStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(order.getExpertId());
                cell2.setCellStyle(contentStyle);

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(order.getAmount().doubleValue());
                cell3.setCellStyle(contentStyle);

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(getOrderStatusText(order.getStatus()));
                cell4.setCellStyle(contentStyle);

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(order.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                cell5.setCellStyle(contentStyle);
            }

            // 设置列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.setColumnWidth(i, 20 * 256);
            }

            // 设置响应头
            String filename = String.format("订单数据_%s.xlsx",
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFilename);

            // 写入响应流
            workbook.write(response.getOutputStream());

            log.info("成功导出订单数据, 共{}条记录", orders.size());
        } catch (IOException e) {
            log.error("导出订单数据失败", e);
            throw new BusinessException("导出订单数据失败");
        }
    }

    /**
     * 创建表头样式
     */
    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        // 设置居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 创建内容样式
     */
    private CellStyle createContentStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        // 设置居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(Integer status) {
        switch (status) {
            case 0:
                return "待接单";
            case 1:
                return "服务中";
            case 2:
                return "已完成";
            case 3:
                return "售后中";
            case 4:
                return "已取消";
            default:
                return "未知状态";
        }
    }
}